﻿# -*- encoding: utf-8 -*-
import requests
import re
import execjs

HEADERS = {
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'Cookie': 'BAIDUID=990798224F507AA5DDAC6D3CAFBBF201:FG=1; BAIDUID_BFESS=990798224F507AA5DDAC6D3CAFBBF201:FG=1; APPGUIDE_10_0_2=1; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1661347822; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1661347974; BIDUPSID=990798224F507AA5DDAC6D3CAFBBF201; PSTM=1661350244; H_PS_PSSID=36543_37110_36884_34813_37003_36570_37070_37238_37136_37055_26350_36864_37205; delPer=0; PSINO=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BA_HECTOR=8h2081al002580a5ak0i6fdk1hgccb616; ZFY=eNoHusuPjLyZRum7f6l4sGCkFFnZU5i34XKjt:BP3oG8:C; ab_sr=1.0.1_YWYxMzVlY2I1OGE0ODM5YTI1NmQ3ZjBlYjVkOTBhZTNlNDUwYjhlZjZiYzM1ZWY1MmE3MDI3OTBiM2E0OWJiYzI0ZDEyOTg0OGUwNGI5ZjVjZDdkNGQxNTZlYmE0YzE5ZmVjYTc3ODY5MGY1NTc4YjdjYWE1MmZjMmMyYzRlMmUzODE5N2Q2OTc1NjkyYTQzMDE0MGI0MWJmMjI3ZDgxMA==; BAIDUID=6F96E295097EFBD58BDD5D9A57EF79F2:FG=1; BAIDUID_BFESS=6F96E295097EFBD58BDD5D9A57EF79F2:FG=1',
  'Origin': 'https://fanyi.baidu.com',
  'Pragma': 'no-cache',
  'Referer': 'https://fanyi.baidu.com/?aldtype=16047',
  'Sec-Fetch-Site': 'same-origin',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
  'X-Requested-With': 'XMLHttpRequest',
  'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"Windows"'
}



def get_token():
    url = "https://fanyi.baidu.com/"
    params = {
        "aldtype": "16047"
    }
    response = requests.get(url, headers=HEADERS, params=params)
    # print(response.text)
    pattern = """window\['common'\] = {
    
    
    
    token: '(.*?)',"""
    token = re.findall(pattern, response.text, re.S)[0]
    return token


keyword = input("请输入需要翻译的词：")
with open('百度sign.js', 'r', encoding='utf-8') as f:
    js = f.read()
sign = execjs.compile(js).call('tl', keyword)

with open('Acs-token.js', 'r', encoding='utf-8') as f:
    js = f.read()
acs_token = execjs.compile(js).call('translate', keyword)
# print(acs_token)
HEADERS.update({'Acs-Token':acs_token})
url = "https://fanyi.baidu.com/v2transapi"
params = {
    "from": "zh",
    "to": "en"
}
data = {
    "from": "zh",
    "to": "en",
    "query": keyword,
    "transtype": "realtime",
    "simple_means_flag": "3",
    "sign": sign,
    "token": get_token(),
    "domain": "common"
}
response = requests.post(url, headers=HEADERS, params=params, data=data)

translate_word = response.json()['trans_result']['data'][0]['dst']
print('翻译结果：',translate_word)
